import React, { Component } from 'react';
import { Table, Input, Modal, Form, Icon, Button, message, Popconfirm, Checkbox, Row, Col, Tree } from 'antd';
import Http from '../../../utils/http';
import { getAllTypeList, RoleBindPlate } from '../../../services/fetch';
import { withRouter } from "react-router-dom";
import { connect } from 'dva';

const FormItem = Form.Item;
const TreeNode = Tree.TreeNode;
@connect(({ video }) => ({
    video,
}))
class UserRole extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dataSource: [],
            total: '',
            visible: false,
        }
        this.http = this.http.bind(this)
    }
    // 获取角色列表
    http = () => {
        Http('/fcinformation/Role/roleList', 'get', { index: '1' })
            .then((res) => {
                if (res.code === 200) {
                    this.setState({
                        dataSource: res.data.list,
                        total: res.data.total
                    })
                }
                if (res.code === 501) {
                    // alert('请登陆！')
                    this.props.history.push('/login')
                }
                if (res.code === 500) {
                    message.error(res.msg)
                }
            })
            .catch((err) => {
                console.log(err)
            })
    }
    componentDidMount() {
        this.http()
    }
    showModal = () => {
        this.setState({
            visible: true,
        });
    }
    //   用户新增
    handleOk = (e) => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let data = { role_name: values.role_names }
                Http('/fcinformation/Role/addRole', 'post', data)
                    .then((res) => {
                        if (res.code === 200) {
                            message.success('角色新增成功！')
                            this.http()
                            this.props.form.resetFields()
                        }
                        if (res.code === 500) {
                            message.error(res.msg)
                        }
                    })
                    .catch((err) => {
                        console.log(err)
                    })
                this.setState({
                    visible: false,
                });
            }
        })
    }
    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }
    // 删除
    deleteRole = (record) => {
        Http('/fcinformation/Role/deleteRole', 'post', { role_id: record.role_id })
            .then((res) => {
                if (res.code === 200) {
                    message.success('角色删除成功！')
                    this.http()
                } else {
                    message.error(res.msg)
                }
            })
            .catch((err) => {
                console.log(err)
            })
    }
    render() {
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;

        const columns = [{
            title: '角色ID',
            dataIndex: 'role_id',
            key: 'role_id',
        }, {
            title: '角色名称',
            dataIndex: 'role_name',
            key: 'role_name',
        }, {
            title: '操作',
            width: '500px',
            align: 'center',
            render: (record) => {
                return (
                    <div>
                        <UserRoleChanges record={record} http={this.http} />

                        <Popconfirm placement="leftTop" title='确定删除？' icon={null} onConfirm={() => this.deleteRole(record)} okText="确定" cancelText="取消">
                            <Button type='danger' size='small'>删除</Button>
                        </Popconfirm>

                        <UserBindRight id={record.role_id} plate_id={record.plate_id} nameShow={record.role_name} />
                    </div>
                )
            }
        },];
        return (
            <div className='UserRole userAll'>
                <div className='head'>
                    <p>角色列表</p>
                </div>
                <div className='addUser'>

                    <Button type="primary" style={{ marginLeft: '-10px' }} onClick={this.showModal}>新增角色</Button>

                    <Modal
                        title="新增"
                        visible={this.state.visible}
                        onOk={this.handleOk}
                        onCancel={this.handleCancel}
                        okText='确认'
                        cancelText='取消'
                    >
                        <Form layout="inline" onSubmit={this.handleSubmit}>
                            <FormItem
                                label='角色名称'
                            >
                                {getFieldDecorator('role_names', {
                                    rules: [{ required: true, message: '请输入角色名!' }],
                                })(
                                    <Input style={{ width: 350 }} placeholder='请输入角色名' />
                                )}
                            </FormItem>
                        </Form>
                    </Modal>
                </div>
                <Table columns={columns} dataSource={this.state.dataSource} bordered
                    pagination={false}
                />
            </div>
        )
    }
}
const UserRoles = Form.create()(UserRole)
export default withRouter(UserRoles)



@connect(({ video }) => ({
    video,
}))
class UserRoleChange extends Component {
    state = {
        visibleChange: false,
        role_id: '',
        role_name: ''
    }
    //   修改 model
    showModalChange = () => {
        // alert(record)
        let record = this.props.record
        this.setState({
            visibleChange: true,
            role_id: record.role_id,
            role_name: record.role_name
        });
        this.props.form.setFieldsValue({
            role_name: record.role_name
        });
    }
    handleCancel = (e) => {
        this.setState({
            visibleChange: false
        });
    }
    handleOkChange = () => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values['role_id'] = this.state.role_id
                Http('/fcinformation/Role/updateRole', 'post', values)
                    .then((res) => {
                        if (res.code === 200) {
                            message.success('角色修改成功！')
                            this.props.http()
                            this.props.form.resetFields()
                        }
                        if (res.code === 500) {
                            message.error(res.msg)
                        }
                    })
                    .catch((err) => {
                        console.log(err)
                    })
                this.setState({
                    visibleChange: false,
                });
            }
        })
    }
    render() {
        const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;

        return (
            <div style={{ display: 'inline-block' }}>

                <Button style={{ marginRight: '10px' }} type='default'
                    size='small' onClick={this.showModalChange}>修改</Button>

                <Modal
                    title="修改"
                    visible={this.state.visibleChange}
                    onOk={this.handleOkChange}
                    onCancel={this.handleCancel}
                    okText='确认'
                    cancelText='取消'
                >
                    <Form layout="inline">
                        <FormItem
                            label='角色名称'
                        >
                            {getFieldDecorator('role_name', {
                                rules: [{ required: true, message: '请输入角色名!' }],
                            })(
                                <Input style={{ width: 350 }} />
                            )}
                        </FormItem>

                    </Form>
                </Modal>
            </div>
        )
    }
}
const UserRoleChanges = Form.create()(UserRoleChange)


@connect(({ video }) => ({
    video,
}))
class UserBindRight extends Component {
    state = {
        visible: false,
        visiblePlate: false,
        options: [],
        checkedKeys: [],
        checkedKeysPlate: this.props.plate_id ? this.props.plate_id.split(',') : [],
        plateList: [],
        yName: '',
    }

    showModal = () => {
        // 获取权限列表
        Http('/fcinformation/Privilege/privilegeList', 'get', { index: '1' })
            .then((res) => {
                if (res.code === 200) {
                    console.log(res)
                    let treeData = []
                    res.data.map((item, index) => {
                        treeData[index] = {
                            title: item.privilege_name,
                            key: String(index),
                            privilege_id: item.privilege_id,
                            children: []
                        }
                        if (item.children) {
                            item.children.map((i, num) => {
                                treeData[index].children[num] = {
                                    title: i.privilege_name,
                                    key: String(index) + '-' + String(num),
                                    privilege_id: i.privilege_id,
                                }
                            })
                        }
                    })
                    this.setState({
                        options: treeData
                    })
                    // 获取用户已有权限
                    Http('/fcinformation/Role/rolePrivilege', 'get', { role_id: this.props.id })
                        .then((ress) => {
                            let idss = []
                            if (ress.code === 200) {
                                ress.data.map((it, cc) => {
                                    treeData.map((item, index) => {
                                        item.children.map((i, ss) => {
                                            if (i.privilege_id === it) {
                                                idss.push(i.key)
                                            }
                                        })
                                    })
                                })
                                this.setState({
                                    checkedKeys: idss
                                })
                            }
                            if (res.code === 500) {
                                message.error(res.msg)
                            }
                        })
                        .catch((err) => {
                            console.log(err)
                        })

                }
                if (res.code === 500) {
                    message.error(res.msg)
                }
            })
            .catch((err) => {
                console.log(err)
            })

        this.setState({
            visible: true,
        });
    }

    showPlateModal = () => {
        getAllTypeList().then((res) => {
            if (res.data.code == 200) {
                this.setState({
                    plateList: res.data.data
                })
                this.setState({
                    visiblePlate: true,
                    checkedKeysPlate: this.state.checkedKeysPlate
                })
            }
        })
    }

    handleCancel = (e) => {
        this.setState({
            visible: false,
        });
    }

    handleCancelPlate = (e) => {
        this.setState({
            visiblePlate: false,
        });
    }

    onCheck = (checkedKeys, e) => {
        let privilege_ids = []
        e.checkedNodes.map((item, index) => {
            let id = item.props.privilege_id ? item.props.privilege_id : 'c'
            if (id !== 'c') {
                privilege_ids.push(id)
            }
        })
        let data = {
            role_id: this.props.id,
            privilege_ids: privilege_ids
        }
        //角色绑定权限
        Http('/fcinformation/Role/roleBindPrivilege', 'post', data)
            .then((res) => {
                if (res.code !== 200) {
                    message.error(res.msg)
                }
                this.setState({ checkedKeys });
            })
            .catch((err) => {
                console.log(err)
            })

    }



    renderTreeNodes = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode {...item} />;
        });
    }

    onPlateCheck = (checkedKeysPlate) => {

        let str = checkedKeysPlate.join(',');
        let obj = {
            role_id: this.props.id,
            plate_id: str
        }
        let msg = message.loading('加载中...', 0);
        RoleBindPlate(obj).then((res) => {
            if (res.data.code == 200) {
                setTimeout(msg, 100);
                message.success('操作成功');
            }
        })
        this.setState({
            checkedKeysPlate
        })
    }

    render() {

        return (
            <div style={{ display: 'inline-block' }}>


                <Button size='small' style={{ marginLeft: '10px' }} onClick={this.showModal}>绑定权限</Button>
                <Button size='small' style={{ marginLeft: '10px' }} onClick={this.showPlateModal}>绑定版面</Button>

                <Modal
                    title="绑定权限"
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText='确认'
                    cancelText='取消'
                    width='60%'
                    footer={null}
                >
                    <div>
                        <p><span style={{ marginRight: '20px' }}>角色名称</span>{this.props.nameShow} </p>
                        <div style={{ display: 'flex' }}><span style={{ marginRight: '20px' }}>权限设置</span>
                            <Tree
                                checkable
                                onCheck={this.onCheck}
                                checkedKeys={this.state.checkedKeys}
                            >
                                {this.renderTreeNodes(this.state.options)}
                            </Tree>
                        </div>
                    </div>
                </Modal>
                <Modal
                    title="绑定版面"
                    visible={this.state.visiblePlate}

                    onCancel={this.handleCancelPlate}
                    okText='确认'
                    cancelText='取消'
                    width='60%'
                    footer={null}
                >
                    <div>
                        <p><span style={{ marginRight: '20px' }}>角色名称</span>{this.props.nameShow} </p>
                        <div style={{ display: 'flex' }}><span style={{ marginRight: '20px' }}>版面设置</span>

                            <Tree
                                checkable
                                onCheck={this.onPlateCheck}
                                checkedKeys={this.state.checkedKeysPlate}
                            >
                                {this.state.plateList.map((item, key) => {
                                    let child = item.children ? item.children : [];
                                    return (
                                        <TreeNode title={item.plate_name} key={item.plate_id} item={item}>
                                            {child.map((item2, k2) => {
                                                return (
                                                    <TreeNode title={item2.plate_name} key={item2.plate_id} item={item2}></TreeNode>
                                                )
                                            })}
                                        </TreeNode>
                                    )
                                })}
                            </Tree>
                        </div>
                    </div>
                </Modal>
            </div>
        )
    }
}
